package com.train.webadmin.app.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.collection.CollUtil;
import com.train.common.log.annotation.OperationLog;
import com.train.common.log.model.constant.SysOperationLogType;
import com.github.pagehelper.page.PageMethod;
import com.train.common.core.object.*;
import com.train.common.core.util.*;
import com.train.common.core.constant.*;
import com.train.common.core.annotation.MyRequestBody;
import com.train.webadmin.app.dto.ScoreDetailDto;
import com.train.webadmin.app.model.*;
import com.train.webadmin.app.service.*;
import com.train.webadmin.app.vo.ScoreDetailVo;
import com.train.webadmin.app.vo.ScoreVo;
import com.train.webadmin.config.ApplicationConfig;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.*;

/**
 * 赋分详情操作控制器类。
 *
 * @author xulei
 * @date 2025-03-07
 */
@Tag(name = "赋分详情管理接口")
@Slf4j
@RestController
@RequestMapping("/admin/app/scoreDetail")
public class ScoreDetailController {

    @Autowired
    private ApplicationConfig appConfig;
    @Autowired
    private ScoreDetailService scoreDetailService;
    @Autowired
    private ClassStudentService classStudentService;
    @Autowired
    private SchoolInfoService schoolInfoService;
    @Autowired
    private ClassInfoService classInfoService;
    @Autowired
    private StudentInfoService studentInfoService;

    /**
     * 新增赋分详情数据。
     *
     * @param scoreDetailDto 新增对象。
     * @return 应答结果对象，包含新增对象主键Id。
     */
    @ApiOperationSupport(ignoreParameters = {
            "scoreDetailDto.id",
            "scoreDetailDto.scoreStart",
            "scoreDetailDto.scoreEnd"})
    @SaCheckPermission("scoreDetail.add")
    @OperationLog(type = SysOperationLogType.ADD)
    @PostMapping("/add")
    public ResponseResult<Long> add(@MyRequestBody ScoreDetailDto scoreDetailDto) {
        String errorMessage = MyCommonUtil.getModelValidationError(scoreDetailDto, false);
        if (errorMessage != null) {
            return ResponseResult.error(ErrorCodeEnum.DATA_VALIDATED_FAILED, errorMessage);
        }
        ScoreDetail scoreDetail = MyModelUtil.copyTo(scoreDetailDto, ScoreDetail.class);
        // 验证关联Id的数据合法性
        CallResult callResult = scoreDetailService.verifyRelatedData(scoreDetail, null);
        if (!callResult.isSuccess()) {
            return ResponseResult.errorFrom(callResult);
        }
        scoreDetail = scoreDetailService.saveNew(scoreDetail);
        return ResponseResult.success(scoreDetail.getId());
    }

    /**
     * 更新赋分详情数据。
     *
     * @param scoreDetailDto 更新对象。
     * @return 应答结果对象。
     */
    @ApiOperationSupport(ignoreParameters = {
            "scoreDetailDto.scoreStart",
            "scoreDetailDto.scoreEnd"})
    @SaCheckPermission("scoreDetail.update")
    @OperationLog(type = SysOperationLogType.UPDATE)
    @PostMapping("/update")
    public ResponseResult<Void> update(@MyRequestBody ScoreDetailDto scoreDetailDto) {
        String errorMessage = MyCommonUtil.getModelValidationError(scoreDetailDto, true);
        if (errorMessage != null) {
            return ResponseResult.error(ErrorCodeEnum.DATA_VALIDATED_FAILED, errorMessage);
        }
        ScoreDetail scoreDetail = MyModelUtil.copyTo(scoreDetailDto, ScoreDetail.class);
        ScoreDetail originalScoreDetail = scoreDetailService.getById(scoreDetail.getId());
        if (originalScoreDetail == null) {
            // NOTE: 修改下面方括号中的话述
            errorMessage = "数据验证失败，当前 [数据] 并不存在，请刷新后重试！";
            return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST, errorMessage);
        }
        // 验证关联Id的数据合法性
        CallResult callResult = scoreDetailService.verifyRelatedData(scoreDetail, originalScoreDetail);
        if (!callResult.isSuccess()) {
            return ResponseResult.errorFrom(callResult);
        }
        if (!scoreDetailService.update(scoreDetail, originalScoreDetail)) {
            return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST);
        }
        return ResponseResult.success();
    }

    /**
     * 删除赋分详情数据。
     *
     * @param id 删除对象主键Id。
     * @return 应答结果对象。
     */
    @SaCheckPermission("scoreDetail.delete")
    @OperationLog(type = SysOperationLogType.DELETE)
    @PostMapping("/delete")
    public ResponseResult<Void> delete(@MyRequestBody Long id) {
        if (MyCommonUtil.existBlankArgument(id)) {
            return ResponseResult.error(ErrorCodeEnum.ARGUMENT_NULL_EXIST);
        }
        return this.doDelete(id);
    }

    /**
     * 批量删除赋分详情数据。
     *
     * @param idList 待删除对象的主键Id列表。
     * @return 应答结果对象。
     */
    @SaCheckPermission("scoreDetail.delete")
    @OperationLog(type = SysOperationLogType.DELETE_BATCH)
    @PostMapping("/deleteBatch")
    public ResponseResult<Void> deleteBatch(@MyRequestBody List<Long> idList) {
        if (MyCommonUtil.existBlankArgument(idList)) {
            return ResponseResult.error(ErrorCodeEnum.ARGUMENT_NULL_EXIST);
        }
        for (Long id : idList) {
            ResponseResult<Void> responseResult = this.doDelete(id);
            if (!responseResult.isSuccess()) {
                return responseResult;
            }
        }
        return ResponseResult.success();
    }

    /**
     * 列出符合过滤条件的赋分详情列表。
     *
     * @param scoreDetailDtoFilter 过滤对象。
     * @param orderParam 排序参数。
     * @param pageParam 分页参数。
     * @return 应答结果对象，包含查询结果集。
     */
    @SaCheckPermission("scoreDetail.view")
    @PostMapping("/list")
    public ResponseResult<MyPageData<ScoreDetailVo>> list(
            @MyRequestBody ScoreDetailDto scoreDetailDtoFilter,
            @MyRequestBody MyOrderParam orderParam,
            @MyRequestBody MyPageParam pageParam) {
        if (pageParam != null) {
            PageMethod.startPage(pageParam.getPageNum(), pageParam.getPageSize(), pageParam.getCount());
        }
        ScoreDetail scoreDetailFilter = MyModelUtil.copyTo(scoreDetailDtoFilter, ScoreDetail.class);
        String orderBy = MyOrderParam.buildOrderBy(orderParam, ScoreDetail.class);
        List<ScoreDetail> scoreDetailList =
                scoreDetailService.getScoreDetailListWithRelation(scoreDetailFilter, orderBy);
        return ResponseResult.success(MyPageUtil.makeResponseData(scoreDetailList, ScoreDetailVo.class));
    }

    /**
     * 导入主表数据列表。
     *
     * @param importFile 上传的文件，目前仅仅支持xlsx和xls两种格式。
     * @return 应答结果对象。
     */
    @SaCheckPermission("scoreDetail.import")
    @OperationLog(type = SysOperationLogType.IMPORT)
    @PostMapping("/import")
    public ResponseResult<Void> importBatch(
            @RequestParam Boolean skipHeader,
            @RequestParam("importFile") MultipartFile importFile) throws IOException {
        String filename = ImportUtil.saveImportFile(appConfig.getUploadFileBaseDir(), null, importFile);
        List<ImportUtil.ImportHeaderInfo> headerInfoList = ImportUtil.makeHeaderInfoList(ScoreDetail.class, null);
        // 下面是导入时需要注意的地方，如果我们缺省生成的代码，与实际情况存在差异，请手动修改。
        // 1. 头信息数据字段，我们只是根据当前的主表实体对象生成了缺省数组，开发者可根据实际情况，对headerInfoList进行修改。
        ImportUtil.ImportHeaderInfo[] headerInfos = headerInfoList.toArray(new ImportUtil.ImportHeaderInfo[]{});
        // 2. 这里需要根据实际情况决定，导入文件中第一行是否为中文头信息，如果是可以跳过。这里我们默认为true。
        // 这里根据自己的实际需求，为doImport的最后一个参数，传递需要进行字典转换的字段集合。
        // 注意，集合中包含需要翻译的Java字段名，如: gradeId。
        Set<String> translatedDictFieldSet = new HashSet<>();
        translatedDictFieldSet.add("studentId");
        List<ScoreDetail> dataList =
                ImportUtil.doImport(headerInfos, skipHeader, filename, ScoreDetail.class, translatedDictFieldSet);
        CallResult result = scoreDetailService.verifyImportList(dataList, translatedDictFieldSet);
        if (!result.isSuccess()) {
            // result中返回了具体的验证失败对象，如果需要返回更加详细的错误，可根据实际情况手动修改。
            return ResponseResult.errorFrom(result);
        }
        //TODO: 下面方法的第二个字段列表参数，用于判断导入的数据在数据表是否已经存在，存在则更新，否则插入，如全部新数据，则无需任何修改。
        scoreDetailService.saveNewOrUpdateBatch(dataList, CollUtil.newArrayList(), -1);
        return ResponseResult.success();
    }

    /**
     * 导出符合过滤条件的赋分详情列表。
     *
     * @param scoreDetailDtoFilter 过滤对象。
     * @param orderParam 排序参数。
     * @throws IOException 文件读写失败。
     */
    @SaCheckPermission("scoreDetail.export")
    @OperationLog(type = SysOperationLogType.EXPORT, saveResponse = false)
    @PostMapping("/export")
    public void export(
            @MyRequestBody ScoreDetailDto scoreDetailDtoFilter,
            @MyRequestBody MyOrderParam orderParam) throws IOException {
        ScoreDetail scoreDetailFilter = MyModelUtil.copyTo(scoreDetailDtoFilter, ScoreDetail.class);
        String orderBy = MyOrderParam.buildOrderBy(orderParam, ScoreDetail.class);
        List<ScoreDetail> resultList =
                scoreDetailService.getScoreDetailListWithRelation(scoreDetailFilter, orderBy);
        // 导出文件的标题数组
        // NOTE: 下面的代码中仅仅导出了主表数据，主表聚合计算数据和主表关联字典的数据。
        // 一对一从表数据的导出，可根据需要自行添加。如：headerMap.put("slaveFieldName.xxxField", "标题名称")
        Map<String, String> headerMap = new LinkedHashMap<>(5);
        headerMap.put("id", "id");
        headerMap.put("subjectId", "科目id");
        headerMap.put("classStudentId", "总分数据id");
        headerMap.put("studentIdDictMap.name", "学生id");
        headerMap.put("score", "分数");
        ExportUtil.doExport(resultList, headerMap, "scoreDetail.xlsx");
    }

    /**
     * 查看指定赋分详情对象详情。
     *
     * @param id 指定对象主键Id。
     * @return 应答结果对象，包含对象详情。
     */
    @SaCheckPermission("scoreDetail.view")
    @GetMapping("/view")
    public ResponseResult<ScoreDetailVo> view(@RequestParam Long id) {
        ScoreDetail scoreDetail = scoreDetailService.getByIdWithRelation(id, MyRelationParam.full());
        if (scoreDetail == null) {
            return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST);
        }
        ScoreDetailVo scoreDetailVo = MyModelUtil.copyTo(scoreDetail, ScoreDetailVo.class);
        return ResponseResult.success(scoreDetailVo);
    }

    private ResponseResult<Void> doDelete(Long id) {
        String errorMessage;
        // 验证关联Id的数据合法性
        ScoreDetail originalScoreDetail = scoreDetailService.getById(id);
        if (originalScoreDetail == null) {
            // NOTE: 修改下面方括号中的话述
            errorMessage = "数据验证失败，当前 [对象] 并不存在，请刷新后重试！";
            return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST, errorMessage);
        }
        if (!scoreDetailService.remove(id)) {
            errorMessage = "数据操作失败，删除的对象不存在，请刷新后重试！";
            return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST, errorMessage);
        }
        return ResponseResult.success();
    }

    @PostMapping("/addScoreDetail")
    public ResponseResult<Void> addScoreDetail(@MyRequestBody ScoreVo scoreVo) {
        ClassStudent filter = new ClassStudent();
        filter.setStudentId(scoreVo.getStudentId());
        filter.setClassId(scoreVo.getClassId());
        List<ClassStudent> classStudents = classStudentService.getClassStudentList(filter, "update_time DESC");
        if (classStudents.size() == 0) {
            return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST, "学生班级信息不存在");
        }
        filter = classStudents.get(0);
        filter.setScore(scoreVo.getScore());
        if (!classStudentService.update(filter, classStudents.get(0))) {
            return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST, "赋分失败");
        }
        scoreDetailService.deleteByClassStudentId(filter.getId());
        for (ScoreDetail scoreDetail : scoreVo.getScoreDetails()) {
            scoreDetail.setClassStudentId(filter.getId());
            if (!scoreDetailService.save(scoreDetail)) {
                return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST, "赋分失败");
            }
        }
        return ResponseResult.success();
    }

    @PostMapping("/getScoreDetail")
    public ResponseResult<ScoreVo> getScoreDetail(@MyRequestBody ScoreVo scoreVo) {
        ClassStudent filter = new ClassStudent();
        filter.setStudentId(scoreVo.getStudentId());
        filter.setClassId(scoreVo.getClassId());
        List<ClassStudent> classStudents = classStudentService.getClassStudentList(filter, "update_time DESC");
        if (classStudents.size() == 0) {
            return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST, "学生班级信息不存在");
        }
        filter = classStudents.get(0);
        scoreVo.setScore(filter.getScore());
        SchoolInfo schoolInfo = schoolInfoService.getById(filter.getSchoolId());
        if (schoolInfo != null) {
            scoreVo.setCompanyName(schoolInfo.getName());
            scoreVo.setCertificateNo(filter.getCertificateNo());
        }
        ClassInfo classInfo = classInfoService.getById(filter.getClassId());
        if (classInfo != null) {
            scoreVo.setClassName(classInfo.getClassName());
            scoreVo.setStartTime(classInfo.getStartTime());
            scoreVo.setEndTime(classInfo.getEndTime());
        }
        StudentInfo studentInfo = studentInfoService.getById(filter.getStudentId());
        if (studentInfo != null) {
            scoreVo.setStudentName(studentInfo.getName());
        }
        List<ScoreDetail> scoreDetails = scoreDetailService.getScoreDetailByClassStudentId(filter.getId());
        scoreVo.setScoreDetails(scoreDetails);
        return ResponseResult.success(scoreVo);
    }
}
